//
//  Alert.swift
//  Asman
//
//  Created by 李旭峰 on 5/20/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import UIKit

@objc protocol AlertDelegate: class {
    @objc optional func alert(didSelected title:String?)
}

class Alert: NSObject {
    
    weak var delegate: AlertDelegate?
    
    var isAutoDismiss: Bool = false
    var autoTimeInterval: TimeInterval = 2
    
    private var alertViewController: UIAlertController?
    
    var completion: (() -> ())?
    
    static let `default` = Alert()
    
    func show(title: String? = nil,message: String,actions: [String]? = nil,from vc: UIViewController = UIApplication.shared.keyWindow!.rootViewController!,completion: (() -> Swift.Void)? = nil) {
        let alertVc = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        alertViewController = alertVc
        actions?.forEach({ (title) in
            let action = UIAlertAction(title: title, style: UIAlertAction.Style.default) { (action) in
                self.delegate?.alert?(didSelected: action.title)
                self.dismiss()
            }
            alertVc.addAction(action)
        })
        vc.present(alertVc, animated: true) {
        }
        
        if actions == nil || actions!.isEmpty {
            isAutoDismiss = true
        }
        
        if isAutoDismiss {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + autoTimeInterval) {
                self.dismiss()
            }
        }
    }
    
    @objc func dismiss() {
        isAutoDismiss  = false
        autoTimeInterval = 2
        delegate = nil
        alertViewController?.dismiss(animated: true, completion: {[weak self] in
            self?.completion?()
        })
    }
}
